<template>
	<n-card>
		<template #header>
			<n-space>
				<n-button
					@click="deleteSelectedTags"
					:disabled="selectedTags.length === 0"
					>批量删除</n-button
				>
				<n-button @click="refreshTags">刷新标签</n-button>
				<n-button @click="syncTags">同步标签</n-button>
				<n-button type="primary" @click="createTag">创建标签</n-button>
			</n-space>
		</template>

		<!-- 标签列表 -->
		<n-data-table
			:data="tags"
			:columns="columns"
			:row-key="(row) => row.tagId"
			:checked-row-keys="selectedTags"
			@update:checked-row-keys="updateSelectedTags"
			pagination-position="none"
		>
		</n-data-table>

		<!-- 创建/编辑标签对话框 -->
		<n-modal v-model:show="showTagModal">
			<n-card
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
				"
				:title="tagModalTitle"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<template #header>
					<n-h4>{{ tagModalTitle }}</n-h4>
				</template>
				<n-form :model="tagForm" :rules="tagRules" ref="tagFormRef">
					<n-form-item path="name" label="标签名称">
						<n-input
							v-model:value="tagForm.name"
							placeholder="请输入标签名称"
						/>
					</n-form-item>
				</n-form>

				<template #footer>
					<n-space justify="end" style="margin-top: 20px">
						<n-button @click="showTagModal = false">取消</n-button>
						<n-button type="primary" @click="handleTagSubmit">确定</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>

		<!-- 标签粉丝列表对话框 -->
		<n-modal v-model:show="showSubscriberModal">
			<n-card
				style="
					width: 600px;
					height: 100%;
					position: fixed;
					right: 0px;
					top: 0px;
				"
				title="标签粉丝列表"
				:bordered="false"
				role="dialog"
				aria-modal="true"
			>
				<n-list v-if="tagSubscribers.length > 0">
					<n-list-item
						v-for="subscriber in tagSubscribers"
						:key="subscriber.openId"
					>
						<template #prefix>
							<n-avatar :src="subscriber.avatarUrl" />
						</template>
						<n-thing
							:title="subscriber.nickname"
							:description="subscriber.openId"
						/>
					</n-list-item>
				</n-list>
				<div v-else class="text-center p-4 text-gray-400">暂无粉丝数据</div>
			</n-card>
		</n-modal>
	</n-card>
</template>

<script setup>
	// 在导入语句中添加h函数和缺少的组件
	import { ref, reactive, onMounted, h } from "vue";
	import wechatTagApi from "@server/api/wechatTagApi";
	// 替换 useDialog 为 useMessage
	import { useMessage, NSpace, NButton } from "naive-ui";
	const message = useMessage();

	// 标签列表数据
	const tags = ref([]);
	// 选中的标签
	const selectedTags = ref([]);
	// 对话框状态
	const showTagModal = ref(false);
	const showSubscriberModal = ref(false);
	// 对话框标题
	const tagModalTitle = ref("创建标签");
	// 编辑的标签ID
	const editingTagId = ref(null);
	// 标签粉丝列表
	const tagSubscribers = ref([]);

	// 表单数据
	const tagForm = reactive({
		name: "",
	});

	// 表单规则
	const tagRules = {
		name: {
			required: true,
			message: "请输入标签名称",
			trigger: ["blur", "input"],
		},
	};

	// 表单引用
	const tagFormRef = ref(null);

	// 表格列配置
	const columns = [
		{
			type: "selection",
			width: 60,
			align: "center",
		},
		{
			title: "标签ID",
			key: "tagId",
			width: 100,
		},
		{
			title: "标签名称",
			key: "name",
			width: 200,
		},
		{
			title: "粉丝数量",
			key: "count",
			width: 100,
		},
		{
			title: "创建时间",
			key: "createTime",
			width: 180,
		},
		{
			title: "操作",
			key: "actions",
			width: 200,
			render: (row) =>
				h(NSpace, null, [
					h(
						NButton,
						{ size: "small", onClick: () => editTag(row) },
						{ default: () => "编辑" }
					),
					h(
						NButton,
						{ size: "small", type: "error", onClick: () => deleteTag(row.tagId) },
						{ default: () => "删除" }
					),
					h(
						NButton,
						{ size: "small", onClick: () => viewTagSubscribers(row.tagId) },
						{ default: () => "查看粉丝" }
					),
				]),
		},
	];

	// 获取标签列表 - 修改为使用 useMessage
	const fetchTags = async () => {
		try {
			tags.value = await wechatTagApi.getTagList();
		} catch (error) {
			console.error("获取标签列表失败:", error);
			message.error("获取标签列表失败");
		}
	};

	// 删除标签 - 修改为使用 useMessage
	const deleteTag = async (tagId) => {
		try {
			if (confirm("确定要删除这个标签吗？")) {
				await wechatTagApi.deleteTag(tagId);
				message.success("标签删除成功");
				await fetchTags();
			}
		} catch (error) {
			console.error("删除标签失败:", error);
			message.error("删除标签失败");
		}
	};

	// 批量删除标签 - 修改为使用 useMessage
	const deleteSelectedTags = async () => {
		if (selectedTags.value.length === 0) return;

		try {
			if (confirm(`确定要删除选中的 ${selectedTags.value.length} 个标签吗？`)) {
				for (const tagId of selectedTags.value) {
					await wechatTagApi.deleteTag(tagId);
				}
				message.success("标签批量删除成功");
				selectedTags.value = [];
				await fetchTags();
			}
		} catch (error) {
			console.error("批量删除标签失败:", error);
			message.error("批量删除标签失败");
		}
	};

	// 查看标签粉丝 - 修改为使用 useMessage
	const viewTagSubscribers = async (tagId) => {
		try {
			const openIds = await wechatTagApi.getSubscribersByTagId(tagId);
			// 模拟粉丝数据
			tagSubscribers.value = openIds.map((openId, index) => ({
				openId,
				nickname: `粉丝${index + 1}`,
				avatarUrl: `https://example.com/avatar${index + 1}.jpg`,
				subscribeStatus: 1,
			}));
			showSubscriberModal.value = true;
		} catch (error) {
			console.error("获取标签粉丝失败:", error);
			message.error("获取标签粉丝失败");
		}
	};

	// 同步标签 - 修改为使用 useMessage
	const syncTags = async () => {
		try {
			await wechatTagApi.syncTagsFromWechat();
			message.success("标签同步成功");
			await fetchTags();
		} catch (error) {
			console.error("同步标签失败:", error);
			message.error("同步标签失败");
		}
	};
	// 刷新标签
	const refreshTags = async () => {
		try {
			message.success("标签刷新成功");
			await fetchTags();
		} catch (error) {
			console.error("刷新标签失败:", error);
			message.error("刷新标签失败");
		}
	};

	// 提交标签表单 - 修改为使用 useMessage
	const handleTagSubmit = async () => {
		try {
			if (!tagFormRef.value) return;
			await tagFormRef.value.validate();

			if (editingTagId.value) {
				// 更新标签
				await wechatTagApi.updateTag(editingTagId.value, tagForm.name);
				message.success("标签更新成功");
			} else {
				// 创建标签
				await wechatTagApi.createTag(tagForm.name);
				message.success("标签创建成功");
			}

			showTagModal.value = false;
			await fetchTags();
		} catch (error) {
			console.error("提交表单失败:", error);
			message.error("操作失败，请重试");
		}
	};

	// 更新选中的标签
	const updateSelectedTags = (keys) => {
		selectedTags.value = keys;
	};

	// 创建标签
	const createTag = () => {
		tagModalTitle.value = "创建标签";
		editingTagId.value = null;
		tagForm.name = "";
		showTagModal.value = true;
	};

	// 编辑标签
	const editTag = (tag) => {
		tagModalTitle.value = "编辑标签";
		editingTagId.value = tag.tagId;
		tagForm.name = tag.name;
		showTagModal.value = true;
	};

	// 添加这行代码，确保页面加载时自动获取数据
	onMounted(() => {
		fetchTags();
	});
</script>

<style scoped>
	/* 使用Naive UI默认样式 */
</style>